<?php
/*
 * add by dragon.hu @2015.10.29  upload file
 */

defined('BASEPATH') or die('forbidden');

class Tmpuploadfile_Controller extends Controller {

	private $initdata;
	private $server_list;
    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
		$config = get_config();
		$this->server_list=get_server_list();
//        $path = CONFIGPATH.'/upload.ini';
//        if (file_exists($path)){
//        	$data = parse_ini_file($path, true);
//        	if ($data){
//        		$this->initdata = $data;
//        	}
//        }
        //print_r($this->initdata);
    }

    function index() {
     if (is_submit()) {
     	$serverIds = $_POST['serverIds'];
		 $tmparr=array();
     	if (count($serverIds) != count($this->server_list)){
     		foreach ($serverIds as $k => $v){
     			$tmparr[$k] = $this->server_list[$v];
     		}
     	}else{
     		$tmparr=$this->server_list;
		}

     	//提交后的逻辑
     	switch ($_FILES['upload_file']['error']){
     		case UPLOAD_ERR_INI_SIZE:
     			echo '<script>alert("文件大小超过了服务器限制！");</script>';
     			break;
     		case UPLOAD_ERR_FORM_SIZE:
     			echo '<script>alert("文件大小超过了服务器限制！");</script>';
     			break;
     		case UPLOAD_ERR_PARTIAL:
     			echo '<script>alert("只有部分文件被上传！");</script>';
     			break;
     		case UPLOAD_ERR_NO_FILE:
     			echo '<script>alert("没有文件被上传！");</script>';
     			break;
     		case UPLOAD_ERR_NO_TMP_DIR:
     			echo '<script>alert("找不到临时文件夹！");</script>';
     			break;
     		case UPLOAD_ERR_CANT_WRITE:
     			echo '<script>alert("文件写入失败！");</script>';
     			break;
     		case UPLOAD_ERR_OK:
     			//将utf-8编码转成gb2312，以免中文文件名乱码
     			$upload_dir = './'.iconv("UTF-8", "gb2312", $_FILES['upload_file']['name']);

				if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $upload_dir)){
					//echo '<script>alert("文件上传成功！");</script>';
					//上传到指定ip的FTP服务器并修改对应的数据库表
					$successstr = "";
					for($i = 0; $i < count($tmparr); $i++){
						$url=$tmparr[$i]['SvrOutAddr'].'/update_gamedata';
						$json_result=$this->upload_file($url,$upload_dir);
						$result=json_decode($json_result,true);
						if(!array_key_exists('RetCode',$result)){
							echo "<script>alert(\"failed!!!\");</script>";
							cp_tips('failed');
						}
//						//1.建立一个ftp连接
//						$conn_id = ftp_connect($this->server_list[$i+1]['SvrOutAddr']);
//						if ($conn_id === false){
//							echo '<script>alert("连接ftp服务器失败！");</script>';
//						}else{
//							//2.登录ftp服务器
//							$login_result = ftp_login($conn_id, $this->initdata[$i+1]['ftpusername'], $this->initdata[$i+1]['ftppasswd']);
//							//$login_result == true ? print_r("+"):print_r("-");
//							//exit(0);
//							if ($login_result == false){
//								echo '<script>alert("登录ftp服务器失败！");</script>';
//							}else{
//								//3.上传文件
//								if (ftp_put($conn_id, $upload_dir, $upload_dir, FTP_BINARY)) {
//									//echo "successfully uploaded ".$_FILES['upload_file']['name'];
//									$successstr .= $this->initdata[$i+1]['servername'] . ",";
//									//4.修改db
//									//$this->operateDB($this->initdata[$i+1]['serverpath'], $this->initdata[$i+1]['dbusername'], $this->initdata[$i+1]['dbpasswd']);
//								} else {
//									echo "There was a problem while uploading $file ";
//								}
//							}
//						}
//						ftp_close($conn_id);
					}
					unlink($upload_dir);
					//echo "$successstr success!";
					echo "<script>alert(\"$successstr success!!!\");</script>";
				}else{
					echo '<script>alert("文件移动失败！");</script>';
				}
				break;
     		}
        }
        //$this->view->assign("arealist", $this->form->select("row[area_host]", get_area_list_host(), '', array('id' => 'area_host')));
        for($i = 0; $i < count($this->server_list); $i++){
        	$tmparr[$i] = $this->server_list[$i]['SvrName'];
        }
        $params = array();
        $params = array_merge(array('multiple' => 'multiple', 'class' => 'multiselect'), $params);
        $params['id'] = isset($params['id']) ? $params['id'] : 'serverIds';
        $selected = array_keys($tmparr);
        //$this->view->assign("initinfo", $this->initdata);
        $this->view->assign("serverlist", $this->form->select("serverIds", $tmparr, $selected, $params, false));
        $this->view->display("tmpupload/tmpuploadfile/index");
    }

    private function upload_file($url,$file_name)
	{
		$post = array(
			"SessionID"=>"ewewqw",
			"SessionKey"=>"wqqew",
			"TbName"=>"@$file_name",//这里是要上传的文件，key与后台处理文件对应
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);

		curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_VERBOSE, 0);

		$result=curl_exec($ch);
		curl_close($ch);

		return $result;

	}

    function operateDB($path, $username, $passwd)
    {
    	$conn = mysql_connect($path, $username, $passwd);
    	if (!$conn){
    		die('connect failed' . mysql_error());
    	}
    	mysql_select_db('shouhuzhemen_account', $conn) or die("select database failed" . mysql_error());
    	$sql = "UPDATE test SET test1 = 1 WHERE test2 = 2";
    	mysql_query($sql);
    	mysql_close();
    }
}

?>
